#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib
import mimetypes
import os
import time
import datetime
from email.mime.text import MIMEText  
from email.mime.multipart import MIMEMultipart  
from email.mime.image import MIMEImage 

#获取前一天的时间
def timenow():
    a = datetime.datetime.now() + datetime.timedelta(days=-1)
    x=''
    for i in str(a):
        if i != '-' and i != '':
            x = x + i
    return x[2:8] #例：141218
#根据时间获取日志名
def itemname ():
    FileList = []
    #rootdir = "C:\Windows\System32\LogFiles"
    #文件路径，避免大范围寻找文件和寻找过多的日志文件，请缩小路径
    rootdir = "D:\LogFiles"
    #获取当前时间
    #timeline=time.strftime('%Y%m%d',time.localtime(time.time()))
    for root, subFolders, files in os.walk(rootdir):     
        for f in files:  
            #if f.find(timeline[2:]+".log") != -1:
             if f.find(timenow() + '.log') != -1:
                FileList.append(os.path.join(root, f))  
#    for item in FileList:  
    return FileList  
msg = MIMEMultipart()  
msg['From'] = '*******'  #修改发送人的名字
msg['To'] = '*******'  #修改为接受人得名字
msg['Subject'] = 'Log'  #主题
   
#发送二进制文件
fileName = itemname()
a = len(fileName)
mietxt = ""
if a != 0:
    for i in range(a): 
        #添加附件
        mietxt += fileName[i] + "\n"
        #添加邮件内容
        txt = MIMEText("今日日志\n" + mietxt)
        ctype, encoding = mimetypes.guess_type(fileName[i])  
        if ctype is None or encoding is not None:  
            ctype = 'application/octet-stream'  
            maintype, subtype = ctype.split('/', 1)  
            #添加附件
            att1 = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName[i], 'rb'))[0], _subtype = subtype) 
            #邮件中显示的邮件名
            att1.add_header('Content-Disposition', 'attachment', filename = timenow() + ".log")
            msg.attach(att1)  
            msg.attach(txt) 
else:
    mietxt=MIMEText("今日无日志")
    msg.attach(mietxt) 
    print"发送成功"
       
#发送邮件
smtp = smtplib.SMTP()  
smtp.connect('smtp.qq.com:25') #smtp服务 
smtp.login('*********', '*******')  #用户名，密码
smtp.sendmail('*********', '*********', msg.as_string())#发件人的邮箱，收件人的邮箱
smtp.quit()  
print '发送成功'

  
 
